﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Dexter.Storage;

namespace Dexter.Repository.NHibernate.Configuration {
	internal class NHibernateConfiguration : INHibernateConfiguration {
		readonly IStorageProvider storageProvider;
		NHConfiguration configuration;

		/// <summary>
		/// Initializes a new instance of the <see cref="NHibernateConfiguration"/> class.
		/// </summary>
		/// <param name="storageProvider">The storage provider.</param>
		public NHibernateConfiguration ( IStorageProvider storageProvider ) {
			this.storageProvider = storageProvider;

			var filePath = storageProvider.Combine(storageProvider.PrivateRoot, "Setup\\db.dxt");

			if (storageProvider.FileExist(filePath))
			{
				var file = storageProvider.GetFile(filePath);

				using (var f = file.OpenRead ( )) {
					using (StreamReader sr = new StreamReader ( f )) {
						configuration = sr.ReadToEnd ( ).Deserialize<NHConfiguration> ( );
					}
				}
			}
		}

		public string ConnectionString {
			get { return configuration.ConnectionString;  }
		}

		public string DatabaseType {
			get { return configuration.DatabaseType; }
		}

		public string DatabaseSchema {
			get { return configuration.DatabaseSchema; }
		}

		public string DatabaseTablePrefix {
			get { return configuration.DatabaseTablePrefix; }
		}

		public bool IsConfigured {
			get { return configuration != null; }
		}

		public void SaveConfiguration ( string connectionString , string databaseType , string databaseSchema ,string databaseTablePrefix ) {
			configuration = new NHConfiguration {
				DatabaseSchema = databaseSchema ,
				ConnectionString = connectionString ,
				DatabaseTablePrefix = databaseTablePrefix ,
				DatabaseType = databaseType ,
			};

			var serializedConf = configuration.Serialize ( );

			using ( var ms = new MemoryStream ( ) ) {
				Encoding uniEncoding = Encoding.UTF8;
				ms.Write ( uniEncoding.GetBytes ( serializedConf ) , 0 , serializedConf.Length );
				ms.Seek ( 0 , SeekOrigin.Begin );

				var filePath = storageProvider.Combine(storageProvider.PrivateRoot, "Setup\\db.dxt");

				if(storageProvider.FileExist(filePath))
					storageProvider.DeleteFile(filePath);

				storageProvider.SaveStream(filePath, ms);
			}
		}
	}
}
